package com.ruoyi.orderManagement.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.contractManagement.service.impl.DocContractServiceImpl;
import com.ruoyi.familyManagement.service.impl.DocFamilyServiceImpl;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.orderManagement.aop.Idempotent;
import com.ruoyi.orderManagement.config.AlipayConfig;
import com.ruoyi.teamManagement.service.impl.DocTeamServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.orderManagement.domain.Order;
import com.ruoyi.orderManagement.service.IOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 我的订单Controller
 * 
 * @author lcd
 * @date 2025-08-14
 */
@RestController
@RequestMapping("/orderManagement/docOrder")
@Api(tags = "订单接口")
@Slf4j
public class OrderController extends BaseController
{
    @Autowired
    private IOrderService orderService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private DocContractServiceImpl docContractService;
    @Autowired
    private DocTeamServiceImpl docTeamService;
    @Autowired
    private DocFamilyServiceImpl docFamilyService;

    /**
     * 查询我的订单列表
     */
    @PreAuthorize("@ss.hasPermi('orderManagement:docOrder:list')")
    @GetMapping("/list")
    @ApiOperation("通过用户id查询订单")
   public TableDataInfo list(HttpServletRequest request, @RequestParam(required = false) String orderState)
{
    startPage();
    //从token中获取userId
    LoginUser loginUser = tokenService.getLoginUser(request);
    Long userId =loginUser.getUserId();
    //调用业务层查询订单
    List<Order>  list = orderService.getOrderByUserId(userId, orderState);
    return getDataTable(list);
}

    /**
     * 导出我的订单列表
     */
    @PreAuthorize("@ss.hasPermi('orderManagement:docOrder:export')")
    @Log(title = "我的订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletRequest request,HttpServletResponse response, @RequestParam(required = false) String orderState)
    {
        //从token中获取userId
        LoginUser loginUser = tokenService.getLoginUser(request);
        Long userId =loginUser.getUserId();
        List<Order> list = orderService.getOrderByUserId(userId, orderState);;
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        util.exportExcel(response, list, "我的订单数据");
    }

    /**
     * 获取我的订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('orderManagement:docOrder:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") String orderId)
    {
        return success(orderService.selectOrderByOrderId(orderId));
    }

    /**
     * 新增我的订单
     */
    @PreAuthorize("@ss.hasPermi('orderManagement:docOrder:add')")
    @Log(title = "我的订单", businessType = BusinessType.INSERT)
    @PostMapping
    @Idempotent  //使用幂等注解
    public AjaxResult add(@RequestBody Order order)
    {
        // 设置支付方式为0
        order.setOrderWay("0");
        // 设置支付状态为0
        order.setOrderState("0");
        order.setOrderId(order.getOrderId());
        String orderId = order.getOrderId();
        //修改签约表对应的签约状态为待付款
        docContractService.updateDocContractState2(Long.valueOf(orderId));
        return toAjax(orderService.insertOrder(order));
    }


    /**
     * 修改我的订单
     */
    @PreAuthorize("@ss.hasPermi('orderManagement:docOrder:edit')")
    @Log(title = "我的订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Order order)
    {
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除我的订单
     */
    @PreAuthorize("@ss.hasPermi('orderManagement:docOrder:remove')")
    @Log(title = "我的订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable List<String> orderIds)
    {
        return toAjax(orderService.deleteOrderByOrderIds(orderIds));
    }
    /**
     * 订单支付
     */
    @PostMapping("/pay")
    @ApiOperation("订单支付")
    public ResponseEntity<String> pay(@RequestParam String orderId) {
        //调用业务层支付订单
        String form = orderService.pay(orderId);
        return ResponseEntity.ok(form);
    }

    @Autowired
    private AlipayConfig alipayConfig;


    /**
     * 支付宝异步回调接口
     * http://内网穿透地址/order/notify
     */
    @SneakyThrows
    @PostMapping("/notify")
    public void aliPayNotify(HttpServletRequest request) {
        //获取所有请求参数，重新创建一个Map再封装一次数据
        Map<String, String> params = request.getParameterMap().entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0]));
        
        // 记录所有回调参数，便于调试
        log.info("支付宝回调参数: {}", params);
        
        // 验证签名
        String sign = params.get("sign");
        String contentV1 = AlipaySignature.getSignCheckContentV1(params);
        log.info("待验证签名内容: {}", contentV1);
        log.info("签名值: {}", sign);
        boolean rsa256CheckSignature = AlipaySignature.rsa256CheckContent(contentV1,
                sign, alipayConfig.getAlipayPublicKey(), "UTF-8");
        log.info("签名验证结果: {}", rsa256CheckSignature);
        
        //表示支付成功
        if (rsa256CheckSignature && "TRADE_SUCCESS".equals(params.get("trade_status"))) {
            // 签名验证成功 并且 支付宝回调的状态是成功状态 TRADE_SUCCESS
            log.info("在{}，买家{}进行订单{}的付款，交易名称{}，付款金额{}", params.get("gmt_payment"), params.get("buyer_id"),
                    params.get("out_trade_no"), params.get("subject"), params.get("total_amount"));
            // 支付成功，修改数据库中该订单的状态，out_trade_no即订单ID
            String outTradeNo = params.get("out_trade_no");
            //更新订单状态为已支付
            orderService.updateOrderStatus(outTradeNo, "1");
            //修改团队的签约数量+1
            Long teamId = docContractService.selectTeamIdByOrderId(Long.valueOf(outTradeNo));//获取团队id
            docTeamService.incrementSignedNumber(teamId);
            //修改家当前用户庭表的签约团队
           Order order = orderService.selectOrderByOrderId(outTradeNo);
            if (order != null) {
                Long userId = docContractService.selectUserIdByOrderId(Long.valueOf(outTradeNo));
                if (userId != null) {
                    Long teamId2 = docContractService.selectTeamIdByOrderId(Long.valueOf(outTradeNo));
                    docFamilyService.updateTeamIdByUserId(userId, String.valueOf(teamId2));
                } else {
                    log.error("无法从订单中获取用户ID，订单号: {}", outTradeNo);
                }
            } else {
                log.error("无法查询到订单信息，订单号: {}", outTradeNo);
            }
            //修改签约表对应的签约状态为已付款
            docContractService.updateDocContractState(Long.valueOf(outTradeNo));
            log.info("订单{}支付成功，状态修改为已付款", outTradeNo);
        } else {
            log.error("支付宝支付失败，签名验证结果: {}，交易状态: {}", rsa256CheckSignature, params.get("trade_status"));
        }
    }
   
    


}
